<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑服务类型' : '新增服务类型'"
    width="600px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="服务代码" prop="standardCode">
        <el-input v-model="form.standardCode" />
      </el-form-item>
      <el-form-item label="名称" prop="displayName">
        <el-input v-model="form.displayName" />
      </el-form-item>
      <el-form-item label="平台" prop="platform">
        <el-input v-model="form.platform" />
      </el-form-item>
      <el-form-item label="功能类型" prop="functionType">
        <el-input v-model="form.functionType" />
      </el-form-item>
      <el-form-item label="启用" prop="enabled">
        <el-switch v-model="form.enabled" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import {
  createServiceType,
  updateServiceType
} from "@/api/adminServiceTypeApi";
import { message } from "@/utils/message";
// 控制对话框显示状态
const dialogVisible = ref(false);

// 表单数据，id 为 0 表示新增，非 0 表示编辑
const form = ref({
  standardCode: "",
  displayName: "",
  platform: "",
  functionType: "",
  enabled: true,
  deleted: 0
});
const emits = defineEmits(["refresh"]);

// 基础校验规则
const rules = {
  standardCode: [
    { required: true, message: "请输入服务代码", trigger: "blur" }
  ],
  displayName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  displayImage: [
    { required: true, message: "请输入显示图片", trigger: "blur" }
  ],
  platform: [{ required: true, message: "请输入平台", trigger: "blur" }],
  functionType: [{ required: true, message: "请输入功能类型", trigger: "blur" }]
};

const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
};

// 通过 id 判断是编辑还是新增
const isEdit = computed(() => form.value?.id);

const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      console.log("提交的数据:", form.value);
      if (isEdit.value) {
        // 编辑逻辑处理
        await updateServiceType(form.value);
        message("更新成功！", { type: "success" });
      } else {
        await createServiceType(form.value);
        // 新增逻辑处理
        message("新增成功！", { type: "success" });
      }
      emits("refresh");
      dialogVisible.value = false;
    } else {
      console.log("表单校验失败");
      return false;
    }
  });
};
const open = row => {
  if (row) {
    for (let key in form.value) {
      form.value[key] = row[key];
    }
    form.value.id = row.id;
  }
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
